#! /usr/bin/python
"""Update all repository working directories within current directory."""

# Author:     Alok Bisani
# Created:    4/Nov/2007
# Liecense:   MIT License (See: http://www.opensource.org/licenses/mit-license.php)

import os
from datetime import datetime

COMMAND='find . \( -name .git -o -name .svn -o -name CVS \) -type d'

git_UPDATE = 'git pull'
svn_UPDATE = 'svn update'
cvs_UPDATE = 'cvs update'

base = os.getcwd()
repos=[]
print "### Searching for repositories in", base
start = datetime.now()
for d in os.popen (COMMAND).read().split():
    repos.append (os.path.dirname (d))

# purge repository subdirectories (for svn & cvs)
repos.sort() # now repo top level dir is always before subdirs
i=1
while i < len(repos):
    if repos[i].find (repos[i-1]) == 0:
        del repos[i]
    else: i += 1

print "### Found ", len (repos), "repositories to update."

def update (r):
    """Detect repository type, run update system command."""
    begin = datetime.now()
    cmd = ''
    if os.path.isdir (r + '/.git'):
        cmd = git_UPDATE
    elif os.path.isdir (r + '/.svn'):
        cmd = svn_UPDATE
    elif os.path.isdir (r + '/CVS'):
        cmd = cvs_UPDATE

    if cmd:
        print "## Running", cmd, "in", r
        os.chdir (r)
        os.system (cmd)
        os.chdir (base)
        print "## Took", datetime.now() - begin
    else:
        print "## ERROR: Could not detect repository type", r

for r in repos: update (r)

print "### Done. Took", datetime.now() - start
